<?php
namespace interface\v1;
/*
*请假接口类
*/

use verify;

class workAppClass extends index {
    private const table = 'work_holiday';
    private const page = 'work';
    private const title = '请假申请';
    public array $stateOption = ['草稿','审核中','已通过'];
	/*查询条件*/
	public function search(){
	    $this->code = 1;
		//类型
		$workHols = explode("，",para("workHols"));
		//查询条件
		$data['result'] = array(
			//状态
			"stateOption" => $this->stateOption,
			//分类
			"typeOption" => $workHols,
            "timeOption"=>$this->timeOption
		);
		//返回
        $this->resp['data'] = $data;
	}
    /*列表页*/
    public function list()
    {
        //全等查询数组
        $equal = array(
            "stid" => self::$stid,//员工
            "state" => $this->post('state'),//审批状态
            "type" => $this->post('type'),//审批状态
        );
        //初始化
        $and ='';
        if ($this->post('keyword')) {
            $and .= " and (type like '%".$this->post('keyword')."%' or orderNo like '%".$this->post('keyword')."%')";
        }
        $commitTime = $this->post('commit_time');
        if (!$commitTime) {
            if ($this->post('startDate')) {
                $commitTime = $this->post('startDate');
            }
            if ($this->post('endDate')) {
                $commitTime .= empty($commitTime) ? $this->post('endDate') : ('~' . $this->post('endDate'));
            }
        }
        if ($commitTime) {
            $and .= $this->miniTimeComparison($commitTime);
        }
        //获取查询结果
        $where = search(array("=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => "startTime desc"));
        //数据分析
        $data['result'] = [];
        foreach ($page['array'] as $array) {
            $staff = query("staff", "stid = '$array[stid]'");
            $data['result'][] = array(
                "id" => $array['id'],//ID
                'orderNo'=>$array['orderNo'],
                "staffName" => $staff['name'],//申请人
                "startTime" => $array['startTime'],//开始时间
                "endTime" => $array['endTime'],//结束时间
                "type" => $array['type'],//补卡事由
                "hour" => $array['hour'],//状态
                "state" => $array['state'],//状态
                'time'=>date('m/d',strtotime($array['time']))
            );
        }
        $data['page'] = $page['para'];
        //返回
        $this->code = 1;
        $this->resp['data'] = $data;
    }
    /**
     * 编辑页面
     */
    public function editPage(){
        $id = $this->post('id');
        $info = query(self::table,"id = '$id'");
        $this->code=1;
        $data=[];
        if ($id && empty($info['id'])){
            $this->code = 0;
            $this->resp['warn'] = '未找到此补卡申请';
        }elseif(!empty($info['id'])){
            $data['result'] = [
                'id'=>$id,
                'startTime'=>$info['startTime'],
                'endTime'=>$info['endTime'],
                'type'=>$info['type'],
                'hour'=>$info['hour'],
                'text'=>$info['text'],
            ];
        }

        //类型
        $workHols = explode("，",para("workHols"));
        $data['result']['typeOption'] = $workHols;
        $this->resp['data'] = $data;
    }

    public function commitEdit(){
        $id = $this->post('id') ?: self::getId();
        //赋值
        $field = array(
            "type" => $this->post('type'),
            "startTime" => $this->post('startTime'),
            "hour"=>$this->post('hour'),//请假小时数
            "endTime" => $this->post('endTime'),
            "text" => $this->post('text'),//备注
            "updateTime" => date("Y-m-d H:i:s"),//更新时间
        );
        $annotation = [
            "type" => '分类',
            "startTime" => '开始时间',
            "endTime" =>'结束时间',
            "hour" => '请假小时数',
            "text" => '请假事由',
        ];
        $rules = [
            'type' => 'required',
            'startTime' => 'required',
            'endTime' => 'required',
            'hour' => 'required|numeric',
            'text' => 'required',
        ];
        // 校验是否符合规则
        $vt = new verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $this->resp['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        $info = query(self::table, " id = '" . $id . "' ");
        //判断
        if (!$this->power(self::page, "edit")) {
            $this->resp['warn'] = "权限不足";
        }elseif($field['startTime'] > $field['endTime']){
            $this->resp['warn'] = "结束时间不得小于开始时间";
        }elseif(sqlNum("work_holiday"," stid = '".$this->control['stid']."' and startTime < '$field[endTime]' and endTime > '$field[startTime]' and id != '".$this->post('id')."' ") > 0){
            $this->resp['warn'] = "你之前的请假申请与当前时间存在交集";
        }elseif (empty($info['id'])) {
            $userNo = self::generateCode(self::page,[
                'prefix' =>'QJSQ' . date('Ymd'),
                'table' => self::table,
                'field' => 'orderNo',
                'where' => '',
            ],$field);
            $department = query('department', " id = '{$this->controlJob['departmentId']}'");
            $field = array_merge($field, array("id" => $id, 'orderNo' => $userNo,'state'=>'草稿','deptName' => $department['name'],'stid' => $this->control['stid'], "time" => date("Y-m-d H:i:s")));
            $this->resp['warn'] = insert(array("table" => self::table, "field" => $field));
        } else {
            $this->resp['warn'] = update(array("table" => self::table, "field" => $field, "where" => "id = '$info[id]'"));
        }
        if (in_array($this->resp['warn'], array("新增成功", "更新成功"))) {
            //添加日志
            $type = mb_substr($this->resp['warn'], 0, 2, 'utf-8');
            $text = $this->control['name'] . $type . "了".self::title."ID：" .$id;
            $this->logText(array("type" => self::page, "text" => $text));
            $this->resp['data']['id'] = $id;
            //返回
            $this->code = 1;
        }
        resp:
    }
	/*详情页*/
	public function detail(){
        $id = $this->post('id');
        $info = query(self::table, "id = '" . $id . "'");
        if (empty($id)) {
            $this->resp['warn'] = "ID为空";
        } elseif (empty($info['id'])) {
            $this->resp['warn'] = "未找到此请假记录";
        } else {
            //申请人
            $staff = query("staff", "stid = '$info[stid]'");
            $audit = query('audit',"targetId = '$info[id]' and flowName = '请假申请'");
            $record = auditAppClass::auditRecord(self::table,$id);
            $auditRecord = [];
            $active = 0;
            if ($record !==false){
                $auditRecord = $record['record'];
                $active = $record['active'];
            }
            $data['result'] = [
                'id'=>$id,
                'staffName'=>$staff['name'],
                'flowName'=>'请假申请',
                'ico'=>root.$this->control['ico'].'?v='.$this->control['updateTime'],
                'orderNo'=>$info['orderNo'],
                'text'=>$info['text'],
                'startTime'=>$info['startTime'],
                'endTime'=>$info['endTime'],
                'commitTime'=>$audit['commitTime'],
                'type'=>$info['type'],
                'hour'=>$info['hour'],
                'time'=>$info['time'],
                'deptName'=>$info['deptName'],
                'state'=>$info['state'],
                'stid'=>$info['stid'],
                'role'=>auditAppClass::role(self::table,$id),
                'auditRecord'=>$auditRecord,
                'active'=>$active,
            ];

            //返回
            $this->code = 1;
            $this->resp['data'] = $data;
        }
	}

    /**
     * 删除
     */
    public function delete()
    {
        $id = $this->post('id');
        $info = query(self::table, "id = '$id'");
        if (!$this->power(self::page, 'del')) {
            $this->resp['warn'] = "你没有删除的权限";
        } elseif (empty($info['id'])) {
            $this->resp['warn'] = "未找到此".self::title;
        } elseif ($info['stid'] != self::$stid) {
            $this->resp['warn'] = "这不是你的".self::title;
        } elseif ($info['state'] != '草稿') {
            $this->resp['warn'] = "此".self::title."不是草稿状态，不能删除";
        } else {
            $warn = delete(array('table' => self::table, 'where' => "id = '$id'"));
            if ($warn == '删除成功') {
                //删除audit表记录
                delete(array('table'=>'audit','where'=>"targetId = '$id'"));
                //删除待办事项
                delete(array("table" => "backlog","where" => " typeId = '$id' "));
                //删除审批记录
                delete(array("table" => "auditing_follow","where" => " typeId = '$id' "));
                //删除消息提醒
                delete(array("table" => "message","where" => " typeid = '$id' "));
                //添加记录
                $text = "{$this->control['name']}删除了一条" . self::title . "：ID【{$id}】" . '<br>';
                // 写入日志
                $this->logText(["type" => self::page, "text" => $text]);
                $this->code = 1;
                $this->resp['warn'] = '删除成功';
            } else {
                $this->resp['warn'] = '删除失败';
            }
        }
        resp:
    }
}